package cc.kzc.adminauth.config;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AllAllowCorsFilter extends CorsFilter {

	private static final long MAX_AGE = 3600 * 24;

	public AllAllowCorsFilter() {
		super(getCorsConfSource());
	}

	private static CorsConfigurationSource getCorsConfSource() {

		CorsConfiguration corsConfig = new CorsConfiguration();
		// 重置
		corsConfig.setAllowedOrigins(null);
		corsConfig.setAllowedOriginPatterns(null);
		corsConfig.setAllowedMethods(null);
		corsConfig.setAllowedHeaders(null);
		// 设置默认
		corsConfig.addAllowedOriginPattern("*");
		corsConfig.addAllowedMethod("*");
		corsConfig.setAllowedHeaders(Collections.singletonList("*"));
		corsConfig.setAllowCredentials(true);
		corsConfig.setMaxAge(MAX_AGE);
		//
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", corsConfig);
		return source;
	}

	private static UrlBasedCorsConfigurationSource getBaseCorsConfSource() {
		CorsConfiguration corsConfig = new CorsConfiguration();
		// 重置
		corsConfig.setAllowedOrigins(null);
		corsConfig.setAllowedOriginPatterns(null);
		corsConfig.setAllowedMethods(null);
		corsConfig.setAllowedHeaders(null);
		// 设置
		List<String> allowedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With",
				"XMLHttpRequest");
		List<String> exposedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With",
				"XMLHttpRequest");
		List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
		List<String> allowedOrigins = Arrays.asList("*");
		corsConfig.setAllowedOrigins(allowedOrigins);
		corsConfig.setAllowedMethods(allowedMethods);
		corsConfig.setAllowedHeaders(allowedHeaders);
		corsConfig.setExposedHeaders(exposedHeaders);
		corsConfig.setMaxAge(MAX_AGE);
		corsConfig.setAllowCredentials(true);

		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", corsConfig);
		return source;
	}

}
